package day2;

import java.util.Arrays;
import java.util.Scanner;

//ctrl+n 快捷键 快速创建
//自定义栈
public class MyStack {
	//栈 自定义类（没用存储数据的特性）
	private int[] arr;//存数据
	private int top;//栈顶
	private int size;//栈中的数量
	//初始化变量
	public MyStack(int n) {
		arr = new int[n];
		top = -1;
		size = 0;
		
	}
	public boolean ifFull() {
		//扩容 数组 5 10 
		
		return top == arr.length-1;
	}
	
	public boolean isEmpty() {
		return top == -1;
		
	}
	//压栈 往栈中添加值
	public void push(int x) {
		//下标从0一直在变
		//如果栈满了
		if(ifFull()) {
			grow();
			
			System.out.println("栈满");
			throw new RuntimeException("栈满了");
		}
		size++;
		arr[++top] = x; //1
	}private void grow() {
		//数组容量确定 不可改变
		//创建新的数组
	int[] arrNew = new int[arr.length*2];
	for (int i = 0; i < arrNew.length; i++) {
		arrNew[i] = arr[i];//五个值+五个0
		
	}
		//栈使用新数组
	arr = arrNew;
	////赋值数组 数组以及里面的值也赋值
	arr = Arrays.copyOf(arr, arr.length*2);
		// TODO Auto-generated method stub
		
	}
	//弹栈  把栈顶的值删除（逻辑删除）
	public int pop() {
		//int temp =arr[top];//删除的值
		//栈是否为空栈
		if(isEmpty()) {
			//System.out.println("栈空");
			//return ;
		throw new RuntimeException("栈空");
		}
		size--;
		return arr[top--];
	}
	//查看栈顶数据
	public int peek() {
		//栈是否为空栈
				if(isEmpty()) {
					//System.out.println("栈空");
					//return ;
				throw new RuntimeException("栈空");
				}
				
		return arr[top];
	}
	//查看栈的容量
	public int size() {
		return size;
	}
	//遍历栈
	public void print() {
		for (int i = top; i >= 0; i--) {
			System.out.println(arr[i]);
			
		}
	}
	//功能 查看栈中的数据
	public static void main(String[] args) {
		MyStack stack = new MyStack(5);
		Scanner sc = new Scanner(System.in);
		boolean flag = true;
		while(flag) {
			System.out.println("请输入命令");
			System.out.println("1(压栈) 2(弹栈) 3(看栈项) 4(栈大小) 5(遍历栈) exit(退出)");
             String command = sc.next();
             switch (command) {
             case "1":
            	 stack.push((int)(Math.random()*10));
            	 break;
             case "2":
            	 int pop = stack.pop();
            	 System.out.println("弹出"+pop);
            	 break;
             case "3":
            	 int peek = stack.peek();
            	 System.out.println("查看项顶"+peek);
            	 break;
             case "4":
            	 int size = stack.size();
            	 System.out.println("栈大小"+size);
            	 break;
             case "5":
            	  stack.print();
            	
            	 break;
             case "exit":
            	flag = false;
            	 break;
             }
	
		}
		System.out.println("Byebye!");	
	}

}
